package fr.enseirb.mycub.task;

import java.io.InputStream;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import fr.enseirb.mycub.json.JSONHandler;
import fr.enseirb.mycub.service.UpdateService;
import fr.enseirb.mycub.utils.Constants;
import fr.enseirb.mycub.utils.ParserUtils;

import android.util.Log;

public class GetJSONAsyncTask extends SafeAsyncTask<Boolean> {

	private final String TAG = getClass().getCanonicalName();
	private final String path;
	private final JSONHandler jsonHandler;

	public GetJSONAsyncTask(JSONHandler jsonHandler, String path){
		super();
		this.jsonHandler = jsonHandler;
		this.path = path;
	}

	@Override
	public Boolean call() throws Exception {
		HttpClient client = UpdateService.getHttpClient(jsonHandler.context);
		URI uri = URI.create(path);

		HttpGet post = new HttpGet(uri);

		// Post the request to the server
		//Send the post request... 
		HttpResponse res = client.execute(post);

		final InputStream input = res.getEntity().getContent();
		final String inputString = ParserUtils.getString(input);
		input.close();

		boolean success = jsonHandler.updateLocalDatabase(inputString);
		if(success){
			jsonHandler.registerLastUpdateDate();
		}
		jsonHandler.taskDone();
		 
		return true;
	}

	@Override
	public void onException(Exception e){
		Log.i(TAG, e.getLocalizedMessage());
	}

}
